﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using HIS.Utils;
using HISModels.Entities;
using HISModels.ViewModel;
using System.Configuration;
using Newtonsoft.Json.Linq;


namespace HIS.Controllers.Master {

    public class ItemCategory : HIS.Controllers.AppBaseController {

        #region Fields

        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private RefItemCategory refItemCategory = null;
        #endregion

        #region Items Category
        public ItemCategory() {
            Data.Add("Pagetitle", "Item Category");
            Data.Add("Notification", strNotification);
        }

        [Authorization(RoleAction = "master-items")]
        public override void Index() {
            try {
                Data["Pagetitle"] += " :: Item Category List";
                RenderFile("master\\items\\itemcategory.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void TableList() {
            try {

                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
                string namevalue = HttpContext.Current.Request["namevalue"].NullSafeToString();
                string codevalue = HttpContext.Current.Request["codevalue"].NullSafeToString();

                string ssearch = "namevalue=" + namevalue + ";codevalue=" + codevalue;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //pagingSearch.sSearch = HttpContext.Current.Request["sSearch"];
                if (!string.IsNullOrEmpty(ssearch)) {
                    pagingSearch.sSearch = ssearch;
                } else { pagingSearch.sSearch = Convert.ToString(HttpContext.Current.Request["sSearch"]); }
                pagingSearch.sSearch = ssearch;

                string strUri = string.Empty;
                strUri = Global.ServiceUriDictionary["itemcategorypaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));

                strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void EditCategory() {
            StringReader stringReader = null;
            /// Get id record from querystring
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                /// Throw to list if something goes wrong
                GoToUrl("itemcategory/"); return;
            }

            try {
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["itemcategory"] + id + Global.ServiceUriDictionary["requestformat"];
                ///Get Rest///
                stringReader = base.RestService.GetJson(strUri);
                ///Deserialize json response to object///
                refItemCategory = JsonConvert.DeserializeObject<RefItemCategory>(stringReader.ReadToEnd());
                ///Set variable for rendering on view HTML///

                refItemCategory.SetNullToEmptyString();
                Data["Pagetitle"] += " :: Edit Item Category ::";
                Data.Add("refItemCategory", refItemCategory);
                Data.Add("IsCreate", "false");
                Data.Add("Actionform", Data["rooturl"] + "master/itemcategory/editcategory/");
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\items\\editcategory.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]

        public void DeleteCategory() {
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("itemcategory/");
                return;
            }

            try {
                refItemCategory = new HISModels.Entities.RefItemCategory();
                string strUri = Global.ServiceUriDictionary["itemcategory"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                var a = JsonConvert.DeserializeObject<RefItemCategory>(stringReader.ReadToEnd());
                if (strNotification == string.Empty) strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                //RenderFile("Admins\\Actions\\editgroupspecialist.html");
                //stringReader.Dispose();
                //base.RestService.Dispose();


                HttpContext.Current.Response.Redirect(Data["rooturl"] + "master/itemcategory/");

                //GoToUrl("groupspecialist/");

                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void SaveCategory() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try {
                refItemCategory = new RefItemCategory(); Utils.Helper.SetNullToEmptyString(refItemCategory);
                if (HttpContext.Current.Request["IsCreate"] != "true") {
                    int id = 0;
                    try {
                        id = Convert.ToInt32(HttpContext.Current.Request["idem"]);
                    } catch { }
                    strUri = Global.ServiceUriDictionary["itemcategory"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    refItemCategory = JsonConvert.DeserializeObject<RefItemCategory>(stringReader.ReadToEnd());
                }

                refItemCategory.PostHandler<HISModels.Entities.RefItemCategory>();

                strUri = Global.ServiceUriDictionary["itemcategory"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true") {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(refItemCategory));
                } else {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(refItemCategory));
                }
                string temp = stringReader.ReadToEnd();


                refItemCategory = JsonConvert.DeserializeObject<RefItemCategory>(temp);

                if (refItemCategory != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            } catch (Exception ex) {
                //strNotification = "{\"strNotification\": \"" + ex.Message + "\"}";
                HttpContext.Current.Response.Write(ex.Message);
            } finally {

                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void CreateItemCategory() {
            StringReader stringReader = null;
            try {
                Data["Pagetitle"] += " :: Add Item Category ::";
                refItemCategory = new HISModels.Entities.RefItemCategory() { NameValue = string.Empty, CodeValue = string.Empty };
                Data.Add("refItemCategory", refItemCategory);
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\items\\editcategory.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        #endregion


    }

}